//////////////////////////////////////////////////////////////////////////////////////////////////////
//                                  Copyright Adrian Vinca 2008                                     //
//////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.GamerServices;
using System.IO;

namespace TicTacToe
{
    enum MultiplayerRole
    {
        None,
        Server,
        Client
    }

    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        SpriteFont messageFont;

        GamePadState currentState;

        MultiplayerRole multiplayerRole = MultiplayerRole.None;

        NetworkSession networkSession;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            Components.Add(new GamerServicesComponent(this));
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            messageFont = this.Content.Load<SpriteFont>("MessageFont");


            this.Log("Start " + this.GetType().Module.FullyQualifiedName);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            GamePadState previousState = currentState;
            this.currentState = GamePad.GetState(PlayerIndex.One);

            if (currentState.DPad.Up == ButtonState.Pressed && previousState.DPad.Up == ButtonState.Released)
            {
                this.multiplayerRole = MultiplayerRole.Server;
                this.Log("Server");

                this.networkSession = NetworkSession.Create(NetworkSessionType.SystemLink, 1, 2);

                this.networkSession.GamerJoined += new EventHandler<GamerJoinedEventArgs>(networkSession_GamerJoined);
                this.networkSession.GamerLeft += new EventHandler<GamerLeftEventArgs>(networkSession_GamerLeft);
                this.networkSession.GameEnded += new EventHandler<GameEndedEventArgs>(networkSession_GameEnded);
                this.networkSession.GameStarted += new EventHandler<GameStartedEventArgs>(networkSession_GameStarted);
                this.networkSession.SessionEnded += new EventHandler<NetworkSessionEndedEventArgs>(networkSession_SessionEnded);

                this.Log("Session started");
            }

            if (currentState.DPad.Down == ButtonState.Pressed && previousState.DPad.Down == ButtonState.Released)
            {
                this.multiplayerRole = MultiplayerRole.Client;
                this.Log("Client");

                // this.networkSession = NetworkSession.Create(NetworkSessionType.SystemLink, 1, 2);
                this.Log("Looking for sessions...");
                NetworkSession.BeginFind(NetworkSessionType.SystemLink, 1, null, OnSessionsFound, (object)"Searching games");

            }
            base.Update(gameTime);
        }

        void OnSessionsFound(IAsyncResult result)
        {
            this.Log("Session found!!!");

            AvailableNetworkSessionCollection availableSessions = NetworkSession.EndFind(result);

            if (availableSessions.Count == 0)
            {
                this.Log("No games found");
            }
            else
            {
                try
                {
                    this.Log("Joining " + availableSessions[0].HostGamertag + "...");
                    this.networkSession = NetworkSession.Join(availableSessions[0]);
                    this.Log("joined!");

                    this.networkSession.GamerJoined += new EventHandler<GamerJoinedEventArgs>(networkSession_GamerJoined);
                    this.networkSession.GamerLeft += new EventHandler<GamerLeftEventArgs>(networkSession_GamerLeft);
                    this.networkSession.GameEnded += new EventHandler<GameEndedEventArgs>(networkSession_GameEnded);
                    this.networkSession.GameStarted += new EventHandler<GameStartedEventArgs>(networkSession_GameStarted);
                    this.networkSession.SessionEnded += new EventHandler<NetworkSessionEndedEventArgs>(networkSession_SessionEnded);
                }
                catch (NetworkException exception)
                {
                    this.Log("Error " + exception.ToString());
                }
            }
        }


        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            if (this.networkSession!= null)
            {
                this.networkSession.Update();
            }

            Color background = Color.Gray;

            switch (this.multiplayerRole)
            {
                case MultiplayerRole.None:
                    background = Color.Black;
                    break;
                case MultiplayerRole.Server:
                    background = Color.Blue;
                    break;
                case MultiplayerRole.Client:
                    background = Color.Red;
                    break;
            }

            graphics.GraphicsDevice.Clear(background);

            // TODO: Add your drawing code here
            spriteBatch.Begin();

            spriteBatch.DrawString(this.messageFont, message, new Vector2(0, 0), Color.White);

            spriteBatch.End();
            base.Draw(gameTime);
        }

        

        private string message;
        private void Log(string logMessage)
        {
            this.message = logMessage;

            System.Diagnostics.Trace.WriteLine(logMessage);
        }

        void networkSession_SessionEnded(object sender, NetworkSessionEndedEventArgs e)
        {
            this.Log("Session ended");
            if (this.multiplayerRole == MultiplayerRole.Client)
            {
                this.multiplayerRole = MultiplayerRole.None;
                this.networkSession.Dispose();
            }
        }

        void networkSession_GameStarted(object sender, GameStartedEventArgs e)
        {
            this.Log("Game started");
        }

        void networkSession_GameEnded(object sender, GameEndedEventArgs e)
        {
            this.Log("Game ended");
        }

        void networkSession_GamerLeft(object sender, GamerLeftEventArgs e)
        {
            this.Log("Gamer left");
            if (this.multiplayerRole == MultiplayerRole.Client)
            {
                this.multiplayerRole = MultiplayerRole.None;
                this.networkSession.Dispose();
            }
        }

        void networkSession_GamerJoined(object sender, GamerJoinedEventArgs e)
        {
            this.Log("Gamer joined");
        }

    }
}
